import React, { useMemo } from 'react';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';

export interface AuthParams {
  action: string | string[];
}

type PermissionWrapperProps = AuthParams & {
  backup?: React.ReactNode;
};

const ActionWrapper = (
  props: React.PropsWithChildren<PermissionWrapperProps>
) => {
  const { backup, action } = props;
  const actions = useSelector((state: GlobalState) => state.actions);

  const hasPermission = useMemo(() => {
    if (typeof action === 'string') {
      return actions.includes(action);
    }
    if (Array.isArray(action)) {
      return actions.some((value) => action.includes(value));
    }
  }, [actions]);

  if (hasPermission) {
    return <>{convertReactElement(props.children)}</>;
  }
  if (backup) {
    return <>{convertReactElement(backup)}</>;
  }
  return null;
};

function convertReactElement(node: React.ReactNode): React.ReactElement {
  if (!React.isValidElement(node)) {
    return <>{node}</>;
  }
  return node;
}

export default ActionWrapper;
